package com.java.sensors.eventTool;

import com.sensorsdata.analytics.javasdk.SensorsAnalytics;
import com.sensorsdata.analytics.javasdk.exceptions.InvalidArgumentException;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * TODO
 *
 * @author wangff
 * @version 1.0.0
 * @since 2021/08/20 20:06
 */
public class WangffSensorsAnalytics extends SensorsAnalytics {
  Consumer consumer;
  public WangffSensorsAnalytics(Consumer consumer) {
    super(consumer);
    this.consumer = consumer;
  }
  public void track_installation(String distinctId, boolean isLoginId, String eventName, Map<String, Object> properties) throws
      InvalidArgumentException {
    addEvent1(distinctId, isLoginId, (String)null, "track_installation", eventName, properties);
  }

  public void addEvent1(String distinctId, boolean isLoginId, String originDistinceId, String actionType, String eventName, Map<String, Object> properties) throws InvalidArgumentException {

    long time = System.currentTimeMillis();
    if (properties != null && properties.containsKey("$time")) {
      Date eventTime = (Date)properties.get("$time");
      properties.remove("$time");
      time = eventTime.getTime();
    }

    String eventProject = null;
    if (properties != null && properties.containsKey("$project")) {
      eventProject = (String)properties.get("$project");
      properties.remove("$project");
    }

    Map<String, Object> eventProperties = new HashMap();
    if (actionType.equals("track_installation") || actionType.equals("track_signup")) {
      eventProperties.putAll(properties);
    }

    if (properties != null) {
      eventProperties.putAll(properties);
    }

    if (isLoginId) {
      eventProperties.put("$is_login_id", true);
    }

    Map<String, Object> event = new HashMap();
    event.put("type", actionType);
    event.put("time", time);
    event.put("distinct_id", distinctId);
    event.put("properties", eventProperties);
    event.put("_track_id", (new Random()).nextInt());
    if (eventProject != null) {
      event.put("project", eventProject);
    }

    if (actionType.equals("track_installation")) {
      event.put("event", eventName);
    } else if (actionType.equals("track_signup")) {
      event.put("event", eventName);
      event.put("original_id", originDistinceId);
    }
    this.consumer.send(event);
  }
}
